package com.khd.problems_0001_0100;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * 20. 有效的括号
 *
 * @author kehandi
 * @title: Problem_0020_ValidParentheses
 * @projectName algorithm
 * @date 2022/6/5 16:46
 */
public class Problem_0020_ValidParentheses {

    private static final Map<Character, Character> pairs = new HashMap<Character, Character>() {{
        put(')', '(');
        put(']', '[');
        put('}', '{');
    }};

    public static boolean isValid(String s) {
        int n = s.length();
        if (n % 2 == 1) {
            return false;
        }

        // 用栈存储左括号
        Deque<Character> stack = new LinkedList<Character>();
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);


            if (pairs.containsKey(ch)) { // 如果是右括号
                // 栈为空 或者 最后进栈的左括号和当前这个右括号不匹配
                if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
                    return false;
                }

                // 栈不为空，且出栈的左括号和当前这个右括号匹配，则出栈
                stack.pop();
            } else { // 如果是左括号，直接入栈
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        String parentheses = "{[}]";
        System.out.println(isValid(parentheses));
    }
}
